package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPLIST_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryList() {
        String key = CACHE_SHOPLIST_KEY;
        //1.从redis中查询缓存
        String shopListJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopListJson)){
            //3.存在直接返回
            List<ShopType> shoptype = JSONUtil.toList(shopListJson, ShopType.class);
            return shoptype;
        }
        //4.不存在根据id查询数据库
        List<ShopType> shopType = query().orderByAsc("sort").list();
        //5.不存在，返回错误
        if(shopType == null){
            return shopType;
        }
        //6.存在写入redis
        stringRedisTemplate.opsForValue().set(key , JSONUtil.toJsonStr(shopType));
        //7.返回
        return shopType;
    }

}
